package com.dingup.provider.controller.student;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingup.api.Util.DateUtil;
import com.dingup.api.Util.JwtTokenUtil;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.adapter.student.StudentCourseInformationAdapter;
import com.dingup.api.base.HttpResContent;
import com.dingup.api.enums.ExamTypeEnum;
import com.dingup.api.model.classInfo.ClassInfo;
import com.dingup.api.model.lesson.LessonInfo;
import com.dingup.api.model.student.*;
import com.dingup.api.model.sys.SysDept;
import com.dingup.api.model.sys.SysUser;
import com.dingup.provider.mapper.StudentCourseInformationMapper;
import com.dingup.provider.service.classInfo.ClassInfoService;
import com.dingup.provider.service.lesson.LessonService;
import com.dingup.provider.service.student.StudentCourseService;
import com.dingup.provider.service.student.StudentExamService;
import com.dingup.provider.service.student.StudentOtherService;
import com.dingup.provider.service.student.StudentSchoolService;
import com.dingup.provider.service.sys.SysDeptService;
import com.dingup.provider.service.sys.SysUserService;
import com.suyeer.basic.util.BHttpResUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.dingup.api.Util.StreamUtil.distinctByKey;
import static com.dingup.api.base.BaseUtil.saveErrorMsgAndData;
import static com.dingup.api.base.BaseUtil.saveSuccessMsgAndData;

/**
 * Created by wancheng on 2018/8/15.
 */
@RestController()
@RequestMapping("/student")
public class StudentInfoController {

    private static Logger logger = LoggerFactory.getLogger(StudentInfoController.class);

    @Autowired
    StudentSchoolService studentSchoolService;
    @Autowired
    StudentCourseService studentCourseService;
    @Autowired
    StudentExamService studentExamService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysDeptService deptService;
    @Autowired
    StudentOtherService studentOtherService;
    @Autowired
    StudentCourseInformationMapper studentCourseInformationMapper;
    @Autowired
    LessonService lessonService;
    @Autowired
    ClassInfoService classInfoService;


    @RequestMapping(value = "/save_school_info.do", method = RequestMethod.POST)
    public void saveSchoolInfo(HttpServletRequest request, HttpServletResponse response,
                               String studentId,
                               String cityLocated,
                               String schoolLocated,
                               String grade,
                               String schoolTarget,
                               String countryTarget) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("保存学生的学校信息");
        try {
            StudentSchoolInformation studentSchoolInformation = studentSchoolService.getStudentSchoolInformationByStudentId(studentId);
            if (studentSchoolInformation != null) {
                throw new Exception("已存在当前学生的学校信息");
            }
            studentSchoolInformation = new StudentSchoolInformation();
            studentSchoolInformation.setUserId(studentId);
            studentSchoolInformation.setCityLocated(cityLocated);
            studentSchoolInformation.setCountryTarget(countryTarget);
            studentSchoolInformation.setGrade(grade);
            studentSchoolInformation.setSchoolLocated(schoolLocated);
            studentSchoolInformation.setSchoolTarget(schoolTarget);
            Date date = new Date();
            studentSchoolInformation.setCreateTime(date);
            studentSchoolInformation.setUpdateTime(date);
            studentSchoolService.saveStudentSchool(studentSchoolInformation);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update_school_info.do", method = RequestMethod.POST)
    public void updateSchoolInfo(HttpServletRequest request, HttpServletResponse response,
                                 Integer id,
                                 String cityLocated,
                                 String schoolLocated,
                                 String grade,
                                 String schoolTarget,
                                 String countryTarget) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("保存学生的学校信息");
        try {
            StudentSchoolInformation studentSchoolInformation = new StudentSchoolInformation();
            studentSchoolInformation.setId(id);
            studentSchoolInformation.setCityLocated(cityLocated);
            studentSchoolInformation.setCountryTarget(countryTarget);
            studentSchoolInformation.setGrade(grade);
            studentSchoolInformation.setSchoolLocated(schoolLocated);
            studentSchoolInformation.setSchoolTarget(schoolTarget);
            studentSchoolInformation.setUpdateTime(new Date());
            studentSchoolService.updateSchoolInformation(studentSchoolInformation);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_school_info_by_studentId.do", method = RequestMethod.POST)
    public void getSchoolInfo(HttpServletRequest request, HttpServletResponse response,
                              String studentId) {
        HttpResContent<StudentSchoolInformation> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取学生的学校信息");
        try {
            StudentSchoolInformation studentSchoolInformation = studentSchoolService.getStudentSchoolInformationByStudentId(studentId);
            saveSuccessMsgAndData(hrc, studentSchoolInformation);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/save_course_info.do", method = RequestMethod.POST)
    public void saveCourseInfo(HttpServletRequest request, HttpServletResponse response,
                               String studentId,
                               String channel,
                               Boolean ifRenewStudent,
                               String introducer,
                               Integer contributionAmount,
                               String salerId,
                               Integer lessonId,
                               Integer classId,
                               Long orderTime
    ) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("保存学生的课程信息");
        try {
            String createUserId = RedisUtils.getInstance().getUserId(request);
            StudentCourseInformation studentCourseInformation = new StudentCourseInformation();
            studentCourseInformation.setUserId(studentId);
            studentCourseInformation.setChannel(channel);
            studentCourseInformation.setContributionAmount(contributionAmount);
            studentCourseInformation.setIfRenewStudent(ifRenewStudent);
            studentCourseInformation.setIntroducer(introducer);
            studentCourseInformation.setSalerId(salerId);
            studentCourseInformation.setLessonId(lessonId);
            studentCourseInformation.setClassId(classId);
            if (orderTime != null) {
                studentCourseInformation.setOrderTime(new Date(orderTime));
            }
            studentCourseService.saveStudentCourse(studentCourseInformation, createUserId);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update_course_info.do", method = RequestMethod.POST)
    public void updateCourseInfo(HttpServletRequest request, HttpServletResponse response,
                                 Integer id,
                                 String channel,
                                 Boolean ifRenewStudent,
                                 String introducer,
                                 Integer contributionAmount,
                                 String salerId,
                                 Integer lessonId,
                                 Integer classId,
                                 Long orderTime) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("编辑学生的课程信息");
        try {
            String userId = RedisUtils.getInstance().getUserId(request);
            StudentCourseInformation studentCourseInformation = studentCourseInformationMapper.selectByPrimaryKey(id);
            if (studentCourseInformation == null) {
                throw new Exception("不存在的课程信息");
            }
            studentCourseInformation.setChannel(channel);
            studentCourseInformation.setContributionAmount(contributionAmount);
            studentCourseInformation.setIfRenewStudent(ifRenewStudent);
            studentCourseInformation.setIntroducer(introducer);
            studentCourseInformation.setSalerId(salerId);
            studentCourseInformation.setLessonId(lessonId);
            studentCourseInformation.setClassId(classId);
            if (orderTime != null) {
                studentCourseInformation.setOrderTime(new Date(orderTime));
            }
            studentCourseService.updateStudentCourse(studentCourseInformation, userId);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_course_info_by_studentId.do", method = RequestMethod.POST)
    public void getCourseInfo(HttpServletRequest request, HttpServletResponse response,
                              String studentId) {
        HttpResContent<Map<String, List<StudentCourseInformationAdapter>>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取学生的课程信息 id=" + studentId);
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            Map<String, List<StudentCourseInformationAdapter>> studentCourseInformations = studentCourseService.getStudentCourseByStudentId(studentId, userAccount);
            saveSuccessMsgAndData(hrc, studentCourseInformations);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }

    }

    @RequestMapping("/get_course_info_by_courseId.do")
    public void updateCourseInfo(HttpServletRequest request, HttpServletResponse response,
                                 Integer id) {
        HttpResContent<StudentCourseInformationAdapter> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("根据id获取学生的课程详情");
        try {
            StudentCourseInformationAdapter studentCourseInformation = studentCourseService.getById(id);
            saveSuccessMsgAndData(hrc, studentCourseInformation);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_all_exam.do", method = RequestMethod.POST)
    public void getExam(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<Map<String, Object>>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取考试");
        try {
            List<Map<String, Object>> list = ExamTypeEnum.getAllExam();
            saveSuccessMsgAndData(hrc, list);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_all_exam_subject.do", method = RequestMethod.POST)
    public void getAllExamSubject(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<Map<String, Object>>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取考试");
        try {
            List<Map<String, Object>> list = ExamTypeEnum.getAllExamType(true);
            saveSuccessMsgAndData(hrc, list);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/save_student_exam.do", method = RequestMethod.POST)
    public void saveStudentExam(HttpServletRequest request, HttpServletResponse response,
                                String studentId,
                                String exam,
                                String examTime,
                                String type,
                                String subjectJson,
                                Boolean ifTargetExam) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("保存考试信息");
        try {
            String nameCh = ExamTypeEnum.getDescription(exam);
            if (StringUtils.isEmpty(nameCh)) {
                throw new Exception("非法的考试");
            }
            StudentExamInformation studentExamInformation = new StudentExamInformation();
            studentExamInformation.setCreateTime(new Date());
            studentExamInformation.setExam(exam);
            studentExamInformation.setExamTime(DateUtil.str2Date(examTime, "yyyy-MM-dd"));
            studentExamInformation.setIfTargetExam(ifTargetExam);
            studentExamInformation.setType(type);
            studentExamInformation.setUserId(studentId);

            List<JSONObject> array = JSONArray.parseArray(subjectJson, JSONObject.class);
            List<StudentSubjectInformation> list = new ArrayList<>();
            Integer order = 0;
            for (JSONObject json : array) {
                StudentSubjectInformation s = new StudentSubjectInformation();
                if (ExamTypeEnum.TOTALSCORE.name().equals(json.get("name_en").toString())) {
                    if (!StringUtils.isEmpty(json.get("value").toString())) {
                        studentExamInformation.setTotalSource(Integer.valueOf(json.get("value").toString()));
                    } else {
                        studentExamInformation.setTotalSource(0);
                    }
                } else {
                    s.setNameEn(json.get("name_en").toString());
                    s.setSource(json.get("value").toString());
                    s.setNameCh(json.get("name_ch").toString());
                    s.setCreateTime(new Date());
                }
                if (!StringUtils.isEmpty(s.getNameEn())) {
                    order = order + 1;
                    s.setOrder(order);
                    list.add(s);
                }
            }
            studentExamInformation.setSubjectInformations(list);
            studentExamService.saveStudentExam(studentExamInformation);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }

    }

    @RequestMapping(value = "/get_student_exam.do", method = RequestMethod.POST)
    public void getStudentExam(HttpServletRequest request, HttpServletResponse response,
                               String studentId) {
        HttpResContent<Map<String, List<StudentExamInformation>>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取考试信息");
        try {
            Map<String, List<StudentExamInformation>> map = studentExamService.getStudentExam(studentId);
            saveSuccessMsgAndData(hrc, map);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/delete_student_exam.do", method = RequestMethod.POST)
    public void deleteStudentExam(HttpServletRequest request, HttpServletResponse response,
                                  Integer id) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("删除考试信息");
        try {
            studentExamService.deleteStudentExam(id);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_saler.do", method = RequestMethod.POST)
    public void getSaler(HttpServletRequest request, HttpServletResponse response,
                         String studentId) {
        HttpResContent<List<SysUser>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取该学生所在校区销售信息");
        try {
            List<SysDept> myDept = deptService.getByUser(studentId);
            if (myDept == null || myDept.size() > 1) {
                throw new Exception("学生校区错误");
            }
            List<Long> deptIds = deptService.getChildDeptIds(myDept.get(0).getId());
            List<SysUser> salers = sysUserService.getUserByDeptIds(deptIds);
            List<SysUser> res = new ArrayList<>();
            salers.stream().filter(distinctByKey(SysUser::getUserId)).forEach(
                    user -> {
                        SysUser u = new SysUser();
                        u.setUserId(user.getUserId());
                        u.setUserName(user.getUserName());
                        res.add(u);
                    }
            );
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/save_student_other_information.do", method = RequestMethod.POST)
    public void saveOherInformation(HttpServletRequest request, HttpServletResponse response,
                                    String studentId,
                                    String contacts,
                                    String account,
                                    String remarks) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("保存学生其他信息");
        try {
            StudentOtherInformation studentOtherInformation = studentOtherService.getStudentOtherInformation(studentId);
            if (studentOtherInformation != null) {
                throw new Exception("已存在当前学生的其他信息");
            }
            studentOtherInformation = new StudentOtherInformation();
            studentOtherInformation.setUserId(studentId);
            studentOtherInformation.setContacts(contacts);
            studentOtherInformation.setAccount(account);
            studentOtherInformation.setCreateTime(new Date());
            studentOtherInformation.setRemarks(remarks);
            studentOtherService.saveStudentOtherInformation(studentOtherInformation);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update_student_other_information.do", method = RequestMethod.POST)
    public void updateOherInformation(HttpServletRequest request, HttpServletResponse response,
                                      Integer id,
                                      String contacts,
                                      String account,
                                      String remarks) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("编辑学生其他信息");
        try {

            StudentOtherInformation studentOtherInformation = new StudentOtherInformation();
            studentOtherInformation.setId(id);
            studentOtherInformation.setContacts(contacts);
            studentOtherInformation.setAccount(account);
            studentOtherInformation.setRemarks(remarks);
            studentOtherService.updateStudentOtherInformation(studentOtherInformation);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_student_other_information.do", method = RequestMethod.POST)
    public void getOherInformation(HttpServletRequest request, HttpServletResponse response,
                                   String studentId) {
        HttpResContent<StudentOtherInformation> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取学生其他信息");
        try {
            StudentOtherInformation studentOtherInformation = studentOtherService.getStudentOtherInformation(studentId);
            saveSuccessMsgAndData(hrc, studentOtherInformation);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_course_all_lesson.do", method = RequestMethod.POST)
    public void getCourseLesson(HttpServletRequest request, HttpServletResponse response
    ) {
        HttpResContent<List<LessonInfo>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("学生添加课程中获取全部课程信息");
        try {
            List<LessonInfo> lessonInfos = lessonService.getAllLessonOnShelf();
            saveSuccessMsgAndData(hrc, lessonInfos);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_class_by_lesson_id.do", method = RequestMethod.POST)
    public void getClassByLessonId(HttpServletRequest request, HttpServletResponse response,
                                   Integer lessonId
    ) {
        HttpResContent<List<ClassInfo>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("学生课程信息-根据课程id获取班级");
        try {
            saveSuccessMsgAndData(hrc, classInfoService.getClassByLessonId(lessonId));
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/delete_course_by_id.do", method = RequestMethod.POST)
    public void deleteCourse(HttpServletRequest request, HttpServletResponse response,
                             Integer id
    ) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("学生信息删除课程");
        try {
            studentCourseService.deleteStudentCourse(id);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
}
